package com.example.tactics.service;

import com.example.tactics.note.Areaset;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.HashMap;
import java.util.Map;

/**
 * description : 定义策略实现
 * author :kang
 * create :2021-10-22 18:09:00
 */
@Component
public class ExcelTactics implements ApplicationContextAware {

    //获取自定义注解里的类
    private ApplicationContext applicationContext;

    //装策略模式的
    private static Map<String, Excelhandle> excelhandleMap = new HashMap<>();

    /**
     * 把几个模块装到工厂里
     */
//    static {
//        excelhandleMap.put(AreaType.SUZHO, new HuaianExcelImpl());
//        excelhandleMap.put(AreaType.WUXI, new WuxiExcelImpl());
//        excelhandleMap.put(AreaType.HUAIAN, new HuaianExcelImpl());
//    }

    /**
     * 从工厂里获取策略,根据自定义注解，拿到每个地区的类
     *
     * @param areaType 判断的值
     * @return
     */
    public Excelhandle getExcelhandle(String areaType) {
        Map<String, Excelhandle> excelMap = excelhandleMap();
        Excelhandle excelhandle = excelMap.get(areaType);
        if (excelhandle == null) {
            throw new UnsupportedOperationException(String.format("input eviction is %s ,not support", areaType));
        }
        return excelhandle;
    }

    public Map<String, Excelhandle> excelhandleMap() {
        //判断这个是否存在
        if (CollectionUtils.isEmpty(excelhandleMap)) {               //查找被标注了这个注解的所有类 名称是键，类是值
            Map<String, Object> withAnnotation = applicationContext.getBeansWithAnnotation(Areaset.class);
            for (Object bean : withAnnotation.values()) {
                //instanceof关键字可以判断左边对象是否是右边类或者子类的一个实例
                if (bean instanceof Excelhandle) {
                    String value = bean.getClass().getAnnotation(Areaset.class).value();
                    excelhandleMap.put(value, (Excelhandle) bean);
                }
            }
        }
        return excelhandleMap;
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }
}
